<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button v-permission="'add-role'" type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>

      <!-- 放置table组件 -->
      <el-table :data="roleList" style="width: 100%">
        <el-table-column prop="name" label="角色" width="350px">
          <!-- 在同一个el-table-column中包含两种状态，所以使用作用域插槽 -->
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" width="350px">
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="350px">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="350px">
          <template v-slot="{row}">
            <!-- 编辑状态 -->
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirmRole(row)">确定</el-button>
              <el-button size="mini" type="danger" @click="row.isEdit = false">取消</el-button>
            </template>
            <!-- 非编辑状态 -->
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnSetRole(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" style="margin-left: 10px;" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <el-pagination
          :page-size="roleData.pagesize"
          :current-page="roleData.page"
          layout="prev, pager, next"
          :total="total"
          @current-change="pageChange"
        />
      </el-row>

    </div>
    <AddRole :visible.sync="showDialog" @pushRoleData="pushRoleData" />
    <!-- 这是分配权限的弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- :props 配置选项 -->
      <!-- label	指定节点标签为节点对象的某个属性值 权限的属性值是name-->
      <!-- :default-checked-keys 默认勾选的节点的 key 的数组,它必须配合node-key="id"使用-->
      <!-- 因为permIds变量中存储的都是id，必须el-tree组件知道key是哪个字段，所以设置node-key="id" -->
      <el-tree
        ref="refTreeRef"
        node-key="id"
        :data="permissionData"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <div align="center">
        <el-col>
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { assignPermApi, delRoleApi, getRoleDetailApi, getRoleListApi, updateRoleApi } from '@/api/role'
import AddRole from './components/addRole.vue'
import { getPermissionListApi } from '@/api/permission'
import { transObjToTree } from '@/utils'

export default {
  components: {
    AddRole
  },
  data() {
    return {
      roleData: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      roleList: [],
      showDialog: false,
      // ---------给角色分配权限-----------
      showPermissionDialog: false,
      // 将权限放置在该数组中
      permissionData: [],
      currentRoleId: null,
      // 这里存放的是，角色已获取的权限
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListApi(this.roleData)
      this.roleList = res.rows
      this.total = res.total
      // console.log(res)
      this.roleList.forEach(item => {
        // 给每一个对象添加一个isEdit
        this.$set(item, 'isEdit', false)
        // 给每一个对象添加一个缓存对象
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    pageChange(newPage) {
      this.roleData.page = newPage
      this.getRoleList()
    },
    pushRoleData() {
      this.showDialog = true
      this.getRoleList()
    },
    btnSetRole(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 点击确定时触发
    async confirmRole(row) {
      // 校验
      if (!row.editRow.name && !row.editRow.description) {
        this.$message.error('角色的名称和描述不能为空~')
        return
      } else {
        await updateRoleApi({ id: row.id, ...row.editRow })
        this.$message.success('修改角色成功~')
        // 取消编辑状态,并显示已修改的内容
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      }
    },
    // 删除角色
    async confirmDel(id) {
      await delRoleApi(id)
      // 判断出现最后一页，最后一条数据时
      if (this.roleList.length === 1 && this.roleData.page > 1) {
        this.roleData.page -= 1
      }
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    // 开启分配权限弹层
    async btnPermission(id) {
      // id在修改更新权限时会使用到，所以把id存起来
      this.currentRoleId = id
      // 获取可以分配的所有权限，树形状态
      this.permissionData = transObjToTree(await getPermissionListApi(), 0)
      // 获取对角色早已分配好的权限
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPermApi({
        id: this.currentRoleId,
        /**
         * this.$refs.refTreeRef.getCheckedKeys()
         * 这里使用的是this.$refs.refTreeRef.getCheckedKeys()，而并非this.permIds
         * 是因为，我们要把更改后的权限放到permIds中，而this.permIds是最初未改的权限
         */
        permIds: this.$refs.refTreeRef.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
  .role-operate {
  padding: 10px;
}
</style>

